package com.dxyxx.framework;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.Header;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.type.JavaType;

import zrc.widget.SimpleFooter;
import zrc.widget.SimpleHeader;
import zrc.widget.ZrcListView;
import zrc.widget.ZrcListView.OnStartListener;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Parcelable;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.android.customized.PullDownView;
import com.dxyxx.R;
import com.dxyxx.dialog.AgainPlayer;
import com.dxyxx.pojo.Comment;
import com.dxyxx.pojo.CommentRecords;
import com.dxyxx.pojo.ResponseResult;
import com.http.HttpUtil;
import com.loopj.android.http.AsyncHttpResponseHandler;

public class CommentFragment_BAKUP extends BaseFragment {
	private final static String FROM = "from";
	private final static String TIME = "time";
	private final static String TITLE = "title";
	private final static String CONTENT = "content";
	private final static int COUNT = 5;

	private ArrayList<String> msgs;
	private int pageId = -1;
	private MyAdapter2 adapter;

	private static final String[][] names = new String[][] { { "加拿大", "瑞典", "澳大利亚", "瑞士", "新西兰", "挪威", "丹麦", "芬兰", "奥地利", "荷兰", "德国", "日本", "比利时", "意大利", "英国" }, { "德国", "西班牙", "爱尔兰", "法国", "葡萄牙", "新加坡", "希腊", "巴西", "美国", "阿根廷", "波兰", "印度", "秘鲁", "阿联酋", "泰国" }, { "智利", "波多黎各", "南非", "韩国", "墨西哥", "土耳其", "埃及", "委内瑞拉", "玻利维亚", "乌克兰" }, { "以色列", "海地", "中国", "沙特阿拉伯", "俄罗斯", "哥伦比亚", "尼日利亚", "巴基斯坦", "伊朗", "伊拉克" } };

	private Handler handler;
	/** 总页数. */
	private int PageCount;
	/** 当前页码. */
	private int PageCurrent;
	/** 被选中的. */
	private int gridID = -1;
	/** 每页显示的数量，Adapter保持一致. */
	private static final float PAGE_SIZE = 12.0f;
	/** GridView. */
	private GridView gridView;
	/** 自定义的左右滑动. */
	private ViewPager vp;
	/** 页码条布局. */
	private LinearLayout layoutBottom;

	/** 页码条. */
	private ImageView imgCur;
	// common private
	// private PullDownView commonView;
	private ListView commonLv;
	private PullDownView privateView;
	private ListView privateLv;
	// private PullDownView otherView;
	// private ListView otherLv;

	private List<View> list;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

		View view = inflater.inflate(R.layout.activity_comment, container, false);

		initViews(view);
		setGrid();
		return view;
		//

	}

	/**
	 * 初始化
	 */
	private TextView commonText;
	private TextView privateText;
	private View commonTab;
	private View privateTab;

	// private TextView otherText;
	// private View otherTab;

	private void initViews(View view) {
		((ImageView) view.findViewById(R.id.backImageButton)).setVisibility(View.INVISIBLE);
		((ImageView) view.findViewById(R.id.nextImageButton)).setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				startActivity(new Intent(getActivity(), com.dynamic.WriteActivity.class));

			}
		});
		((TextView) view.findViewById(R.id.title)).setText("热评");
		sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

		// /-----------init data

		// // init data finished
		list = new ArrayList<View>();
		ImageView homeButton = ((ImageView) view.findViewById(R.id.backImageButton));
		homeButton.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				//MainActivity.moveToSpecifiedTab(getApplicationContext(), 0);
			}
		});
		// 设置tab 变化。
		vp = (ViewPager) view.findViewById(R.id.vp_message_launcher_layout);
		vp.setOnPageChangeListener(new OnPageChangeListener() {

			@Override
			public void onPageSelected(int arg0) {
				setCurPage(arg0);
			}

			@Override
			public void onPageScrolled(int arg0, float arg1, int arg2) {

			}

			@Override
			public void onPageScrollStateChanged(int arg0) {

			}
		});
		commonText = (TextView) view.findViewById(R.id.commonText);
		commonText.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {

				if (vp.getCurrentItem() != 0) {

					vp.setCurrentItem(0);
					System.out.println(vp.getCurrentItem());
				}
			}
		});
		privateText = (TextView) view.findViewById(R.id.privateText);
		privateText.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				if (vp.getCurrentItem() != 1) {

					vp.setCurrentItem(1);
				}
			}
		});
		// otherText = (TextView) findViewById(R.id.otherText);
		// otherText.setOnClickListener(new View.OnClickListener() {
		//
		// @Override
		// public void onClick(View v) {
		// if (vp.getCurrentItem() != 2) {
		//
		// vp.setCurrentItem(2);
		// }
		// }
		// });
		commonTab = view.findViewById(R.id.commonTab);
		privateTab = view.findViewById(R.id.privateTab);
		// otherTab = findViewById(R.id.otherTab);

		layoutBottom = (LinearLayout) view.findViewById(R.id.layout_scr_bottom);

	}

	/**
	 * 添加ListView
	 * 
	 */
	private ZrcListView[] listViews;
	private ViewGroup[] waitViewGroups;
	private View[] containers;;
	private MessageAdapter[] messageAdapters;
	private List<Map<String, String>>[] datas;
	private LayoutInflater mInflater;
	private int[] currentPage = { 1, 1 }; // 当前加载页数

	// **设置listview 头部底部的样式
	private void setStyle(ZrcListView listView) {
		// 设置下拉刷新的样式（可选，但如果没有Header则无法下拉刷新）
		SimpleHeader header = new SimpleHeader(getActivity());
		header.setTextColor(0xff0066aa);
		header.setCircleColor(0xff33bbee);
		listView.setHeadable(header);

		// 设置加载更多的样式（可选）
		SimpleFooter footer = new SimpleFooter(getActivity());
		footer.setCircleColor(0xff33bbee);
		listView.setFootable(footer);

		// 设置列表项出现动画（可选）
		listView.setItemAnimForTopIn(R.anim.topitem_in);
		listView.setItemAnimForBottomIn(R.anim.bottomitem_in);

		// 开启 加载更多多 的功能
		listView.startLoadMore();
	}

	private void setGrid() {
		// 初始化数据
		listViews = new ZrcListView[2];
		waitViewGroups = new ViewGroup[2];
		containers = new View[2];
		messageAdapters = new MessageAdapter[2];
		datas = new List[2];
		// 在这里添加视图。多个自定义的View
		mInflater = LayoutInflater.from(getActivity());
		for (int i = 0; i < 2; i++) {
			waitViewGroups[i] = (ViewGroup) mInflater.inflate(R.layout.fragment_wait, null);
			containers[i] = mInflater.inflate(R.layout.component_comment_mylistview, null);
			listViews[i] = (ZrcListView) containers[i].findViewById(R.id.zListView);
			listViews[i].setDivider(getResources().getDrawable(R.color.common_list_devider_color));
			listViews[i].setDividerHeight(2);

			setStyle(listViews[i]);
			datas[i] = new ArrayList<Map<String, String>>();
			messageAdapters[i] = new MessageAdapter(getActivity(), i, datas[i]);
		}
		String undoneOrderUrl = "comment/minelist?current=1&count=" + COUNT;
		HttpUtil.get(undoneOrderUrl, new DownloadCommentHandler(listViews[0], waitViewGroups[0], messageAdapters[0], 0, false));
		String urlString1 = "comment/list?current=1&count=" + COUNT;
		HttpUtil.get(urlString1, new DownloadCommentHandler(listViews[1], waitViewGroups[1], messageAdapters[1], 1, false));

		for (int i = 0; i < 2; i++) {
			final int index = i;
			// 下拉刷新事件回调（可选）
			listViews[index].setOnRefreshStartListener(new OnStartListener() {
				@Override
				public void onStart() {
					refresh(index);
				}
			});

			// 加载更多事件回调（可选）
			listViews[index].setOnLoadMoreStartListener(new OnStartListener() {
				@Override
				public void onStart() {
					loadMore(index);
				}
			});

		}

		for (ViewGroup temp : waitViewGroups) {
			list.add(temp);
		}
		vp.setAdapter(new MyAdapter());

	}

	private void refresh(int index) {

		String urlString = "comment/list?current=1&count=" + COUNT;
		datas[index] = new ArrayList<Map<String, String>>();

		switch (index) {
		case 0:
			urlString = "comment/minelist?current=1&count=" + COUNT;
			break;
		case 1:
			urlString = "comment/list?current=1&count=" + COUNT;
			break;

		default:

			break;
		}
		HttpUtil.get(urlString, new DownloadCommentHandler(listViews[index], waitViewGroups[index], messageAdapters[index], index, true));

		// adapter.notifyDataSetChanged();
		// listView1.setRefreshSuccess("加载成功"); // 通知加载成功
		// listView1.startLoadMore(); // 开启LoadingMore功能

	}

	private void loadMore(int index) {
		currentPage[index] = currentPage[index] + 1;

		String urlString = "comment/minelist?current=" + currentPage[index] + "&count=" + COUNT;

		switch (index) {
		case 0:
			urlString = "comment/minelist?current=" + currentPage[index] + "&count=" + COUNT;
			break;
		case 1:
			urlString = "comment/list?current=" + currentPage[index] + "&count=" + COUNT;
			break;

		default:

			break;
		}

		HttpUtil.get(urlString, new DownloadMoreCommentHandler(listViews[index], waitViewGroups[index], messageAdapters[index], datas[index], index));

	}

	class MyAdapter extends PagerAdapter {

		@Override
		public int getCount() {
			return list.size();
		}

		@Override
		public boolean isViewFromObject(View arg0, Object arg1) {
			return arg0 == arg1;
		}

		@Override
		public int getItemPosition(Object object) {
			return super.getItemPosition(object);
		}

		@Override
		public void destroyItem(View arg0, int arg1, Object arg2) {
			((ViewPager) arg0).removeView(list.get(arg1));
		}

		@Override
		public Object instantiateItem(View arg0, int arg1) {
			((ViewPager) arg0).addView(list.get(arg1));
			return list.get(arg1);
		}

		@Override
		public void restoreState(Parcelable arg0, ClassLoader arg1) {
		}

		@Override
		public Parcelable saveState() {
			return null;
		}

		@Override
		public void startUpdate(View arg0) {
		}

		@Override
		public void finishUpdate(View arg0) {
		}

	}

	/**
	 * 更新当前页码
	 */
	public void setCurPage(int page) {
		switch (page) {
		case 0:
			commonText.setTextColor(0xffFFD101);
			privateText.setTextColor(0xffcccccc);
			// otherText.setTextColor(0xffcccccc);
			commonTab.setBackgroundColor(getResources().getColor(R.color.theme_color));
			privateTab.setBackgroundColor(getResources().getColor(R.color.transparent));
			// otherTab.setBackgroundColor(getResources().getColor(R.color.transparent));
			break;
		case 1:
			privateText.setTextColor(0xffFFD101);
			commonText.setTextColor(0xffcccccc);
			// otherText.setTextColor(0xffcccccc);
			privateTab.setBackgroundColor(getResources().getColor(R.color.theme_color));
			commonTab.setBackgroundColor(getResources().getColor(R.color.transparent));
			// otherTab.setBackgroundColor(getResources().getColor(R.color.transparent));
			break;
		// case 2:
		// otherText.setTextColor(0xff000000);
		// commonText.setTextColor(0xffcccccc);
		// privateText.setTextColor(0xffcccccc);
		// otherTab.setBackgroundColor(getResources().getColor(R.color.theme_color));
		// commonTab.setBackgroundColor(getResources().getColor(R.color.transparent));
		// privateTab.setBackgroundColor(getResources().getColor(R.color.transparent));
		// break;
		default:
			break;
		}
	}

	// 异步下载信息

	private SimpleDateFormat sdf;

	private ViewHolder holder = null; // 如果缓存convertView为空，则需要创建View

	public class MessageAdapter extends BaseAdapter {
		private List<Map<String, String>> data;
		private int messageType;

		public MessageAdapter(Context context, int messageType, List<Map<String, String>> data) {
			this.mInflater = LayoutInflater.from(context);
			this.data = data;
			this.messageType = messageType;
		}

		// ViewHolder静态类
		private LayoutInflater mInflater = null;

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			Map<String, String> map = this.data.get(position);

			holder = null;

			//int type = getItemViewType(position);
			if (convertView == null) {// 如果缓存convertView为空，则需要创建View
				holder = new ViewHolder();
				// 根据自定义的Item布局加载布局
				switch (messageType) {
				case 0:
					convertView = mInflater.inflate(R.layout.item_comment_listview, null);
					break;
				case 1:
					convertView = mInflater.inflate(R.layout.item_comment_listview, null);
					break;

				default:
					break;
				}
				holder.moneyText = (TextView) convertView.findViewById(R.id.orderMoney);
				holder.dateText = (TextView) convertView.findViewById(R.id.orderDate);
				holder.timeText = (TextView) convertView.findViewById(R.id.orderTime);
				holder.uuidText = (TextView) convertView.findViewById(R.id.orderId);
				holder.detailText = (TextView) convertView.findViewById(R.id.orderDetail);
				holder.thumbImage = (ImageView) convertView.findViewById(R.id.orderThumb);
				convertView.setTag(holder);
			}

			holder = (ViewHolder) convertView.getTag();
			//			holder.moneyText.setText(map.get(MONEY));
			//			holder.dateText.setText(map.get(DATE));
			//			holder.timeText.setText(map.get(TIME));
			//			holder.uuidText.setText(map.get(UUID));
			//			holder.detailText.setText(map.get(DETAIL));
			//			imageLoader.displayImage(map.get(IMAGE), holder.thumbImage, squareOptions, animateFirstListener);

			//convertView.setOnClickListener(new ItemClickListener(map));

			return convertView;
		}

		@Override
		public int getCount() {
			return this.data.size();
		}

		@Override
		public Object getItem(int position) {
			return position;
		}

		@Override
		public long getItemId(int position) {
			return position;
		}
	}

	static class ViewHolder {
		public TextView detailText;
		public TextView timeText;
		public TextView moneyText;
		public TextView dateText;
		public TextView uuidText;
		public ImageView thumbImage;

	}

	private class MyAdapter2 extends BaseAdapter {
		@Override
		public int getCount() {
			return msgs == null ? 0 : msgs.size();
		}

		@Override
		public Object getItem(int position) {
			return msgs.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			TextView textView;
			if (convertView == null) {
				textView = (TextView) getActivity().getLayoutInflater().inflate(android.R.layout.simple_list_item_1, null);
			} else {
				textView = (TextView) convertView;
			}
			textView.setText(msgs.get(position));
			return textView;
		}
	}

	// / 写一个通用的类。
	class DownloadCommentHandler extends AsyncHttpResponseHandler {
		// 需要传进来 ListView 跟waitViewGrop
		private zrc.widget.ZrcListView listView;
		private ViewGroup waitViewGroup;
		private MessageAdapter messageAdapter;
		// private List<Map<String, String>> data;
		private int index;
		private boolean isRefresh;

		public DownloadCommentHandler(zrc.widget.ZrcListView listView, ViewGroup waitViewGroup, MessageAdapter messageAdapter, int index, boolean isRefresh) {
			this.listView = listView;
			this.waitViewGroup = waitViewGroup;
			// this.data = data;
			this.index = index;
			this.messageAdapter = messageAdapter;
			this.isRefresh = isRefresh;
		}

		@Override
		public void onFailure(int arg0, Header[] arg1, byte[] arg2, Throwable arg3) {
			listView.setRefreshSuccess("加载失败");
		}

		@Override
		public void onSuccess(int arg0, Header[] arg1, byte[] responseStr) {
			try {
				JavaType javaType = getObjectMapper().getTypeFactory().constructParametricType(ResponseResult.class, CommentRecords.class);
				ResponseResult<CommentRecords> result = getObjectMapper().readValue(new String(responseStr), javaType);

				List<Map<String, String>> downloadData = new ArrayList<Map<String, String>>();
				//设置 data
				downloadData = setData(index, result);

				// 设置data ends

				datas[index].addAll(downloadData);
				if (!isRefresh) {

					listView.setAdapter(messageAdapter);
					// listView.refresh(); // 主动下拉刷新
					waitViewGroup.addView(containers[index]);

				} else {
					// 刷新

					///messageAdapter.data = datas[index];
					messageAdapter.notifyDataSetChanged();
					listView.setRefreshSuccess("加载成功"); // 通知加载成功
					// 开启 加载更多多 的功能
					//listView.startLoadMore();
				}
			} catch (JsonParseException e) {
				e.printStackTrace();
			} catch (JsonMappingException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}

		}
	}

	// / 写一个通用的类。
	class DownloadMoreCommentHandler extends AsyncHttpResponseHandler {
		// 需要传进来 ListView 跟waitViewGrop
		private zrc.widget.ZrcListView listView;
		private ViewGroup waitViewGroup;
		private MessageAdapter messageAdapter;
		private List<Map<String, String>> data;
		private int index;

		public DownloadMoreCommentHandler(zrc.widget.ZrcListView listView, ViewGroup waitViewGroup, MessageAdapter messageAdapter, List<Map<String, String>> data, int index) {
			this.listView = listView;
			this.waitViewGroup = waitViewGroup;
			this.data = data;
			this.messageAdapter = messageAdapter;
			this.index = index;

		}

		@Override
		public void onFailure(int arg0, Header[] arg1, byte[] arg2, Throwable arg3) {
			AgainPlayer.makeCall(getActivity(), "网络异常");
		}

		@Override
		public void onSuccess(int arg0, Header[] arg1, byte[] responseStr) {
			try {
				JavaType javaType = getObjectMapper().getTypeFactory().constructParametricType(ResponseResult.class, CommentRecords.class);
				ResponseResult<CommentRecords> result = getObjectMapper().readValue(new String(responseStr), javaType);

				List<Map<String, String>> downloaddata = new ArrayList<Map<String, String>>();
				//设置 data
				downloaddata = setData(index, result);

				if (downloaddata.size() == 0) {
					listView.stopLoadMore();
				} else {
					data.addAll(downloaddata);
					messageAdapter.notifyDataSetChanged();
					listView.setLoadMoreSuccess(); // 通知加载成功
				}
			} catch (JsonParseException e) {
				e.printStackTrace();
			} catch (JsonMappingException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}

		}
	}

	private List<Map<String, String>> setData(int index, ResponseResult<CommentRecords> result) {
		List<Map<String, String>> list = new ArrayList<Map<String, String>>();
		for (Comment comment : result.getObject().getRecordList()) {
			Map<String, String> map = new HashMap<String, String>();

			map.put(TIME, sdf.format(comment.getPostTime()));
			
			map.put("id", comment.getId() + "");

			StringBuilder sb = new StringBuilder();

			list.add(map);
		}
		return list;

	}

}